var config = require("../config/config.js");
var api = require("../api/api.js");
var storageManage = require("../manage/storageManage.js");
var md5 = require("md5.js");
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function isEmpty(obj) {
  if (obj == undefined || obj == null || new String(obj).trim() == '') {
    return true;
  } else {
    return false;
  }
}

// 
function isNum(num) {
  var reg = /^\d+(?=\.{0,1}\d+$|$)/
  if (reg.test(num)) return true;
  return false;
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 是否是手机
 */

function isTel(s) {
  if (s != null) {
    var length = s.length;
    if (length == 11 && /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(14[0-9]{1})|)+\d{8})$/.test(s)) {
      return true;
    } else {
      return false;
    }
  }
}
/*获取当前页url*/
function getCurrentPageUrl() {
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  return url
}
//图片预览
function imgMagnifyShow(event, imglist) {
  var src = event.currentTarget.dataset.src;//获取data-src
  wx.previewImage({
    current: src,
    urls: imglist
  })
}
//多张图片上传
function uploadimg(pData, pCompleteBack) {
  var sucImgUrlArr = [];
  var failImgUrlArr = [];
  var that = this;
  var i, success, fail;
  var upOneImg = function (pData, pCompleteBack) {
    i = pData.i ? pData.i : 0,//当前上传的哪张图片
      success = pData.success ? pData.success : 0,//上传成功的个数
      fail = pData.fail ? pData.fail : 0;//上传失败的个数

    const uploadTask = wx.uploadFile({
      url: pData.url,
      filePath: pData.path[i],
      name: 'fileData',//这里根据自己的实际情况改
      formData: {},
      success: (resp) => {
        if (resp.statusCode != 404) {
          success++;//图片上传成功，图片上传成功的变量+1;
          sucImgUrlArr.push(resp.data)
          //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
        } else {
          console.info("404")
          fail++;//图片上传失败，图片上传失败的变量+1
          failImgUrlArr.push(pData.path[i])
        }

      },
      fail: (res) => {
        fail++;//图片上传失败，图片上传失败的变量+1
        failImgUrlArr.push(pData.path[i])
      },
      complete: () => {
        i++;//这个图片执行完上传后，开始上传下一张
        if (i == pData.path.length) {   //当图片传完时，停止调用          
          console.log('执行完毕----成功：' + success + " 失败：" + fail);
          var str;
          if (fail == 0) {
            str = "上传成功";
          } else {
            str = "上传成功:" + success + ",上传失败:" + fail;
          }
          wx.showToast({
            title: str,
            icon: 'none',
            duration: 1000
          })
          var imgData = {
            sucImgUrlArr: sucImgUrlArr,
            failImgUrlArr: failImgUrlArr
          }
          pCompleteBack(imgData)
        } else {//若图片还没有传完，则继续调用函数
          console.log(i);
          pData.i = i;
          pData.success = success;
          pData.fail = fail;
          upOneImg(pData, pCompleteBack);
        }

      }
    });
    uploadTask.onProgressUpdate((res) => {
      // sucBack(res)
      // console.log(res)
      // console.log('上传进度', res.progress)
      // console.log('已经上传的数据长度', res.totalBytesSent)
      // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  }
  upOneImg(pData, pCompleteBack);

}

/**
 * 时间戳
 */
function timeStamp() {
  return parseInt(new Date().getTime() / 1000) + ''
}

// 防止多次点击
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1000
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
    let _nowTime = + new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments)   //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}
/* 随机数 */
function randomString() {
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = chars.length;
  var pwd = '';
  for (var i = 0; i < 32; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

// 调起支付签名
function MixedencryMD5(appid, res_paydata, randomString, timeStamp, key) {
  return "appId=" + appid + "&nonceStr=" + randomString + "&package=prepay_id=" + res_paydata + "&signType=MD5" + "&timeStamp=" + timeStamp + "&key=" + key;
}

function payTap(that, state_id, sucBack, errBack) {
  if (this.isEmpty(storageManage.getGlobalConfig().mch_key)) {
    wx.showToast({
      title: '未开通微信支付!'
    })
    return;
  };

  var data = {
    "order_no": state_id.toString()
  };
  api.default.api('get_wechat_prepay_id', data, function (res) {
    console.log("预支付成功" + JSON.stringify(res));
    if (res.e != 0) {
      errBack(res)
      return false;
    }
    var package_ = "prepay_id=" + res.data.prepay_id;
    var randomStringData = randomString();
    var timeStampData = timeStamp();
    var MixdencryMD5Data = MixedencryMD5(storageManage.getGlobalConfig().appid, res.data.prepay_id, randomStringData, timeStampData, storageManage.getGlobalConfig().mch_key);
    console.log("paysign befor=" + MixdencryMD5Data);
    var paysign = md5.hex_md5(MixdencryMD5Data).toUpperCase();
    console.log("paysign=" + paysign);
    //微信支付接口
    wx.requestPayment({
      timeStamp: timeStampData,
      nonceStr: randomStringData,
      package: package_,
      signType: 'MD5',
      paySign: paysign,
      success: function (res_) {
        console.log("支付成功 " + JSON.stringify(res_));
        sucBack(res_)
      }, fail: function (e) {
        console.error("支付失败 " + JSON.stringify(e));
        wx.showToast({
          title: '支付失败',
          icon: 'none',
          duration: 1000,
          success: function () {
            if (typeof errBack == "function") {
              errBack(e)
            }
          }
        })
      }
    })

  }, function (e, du) {
    console.error("预支付失败" + e + "   " + du);
    wx.showToast({
      title: '支付失败',
      icon: 'success',
      duration: 2000
    })
  });
}
module.exports = {
  formatTime: formatTime,
  isEmpty: isEmpty,
  timeStamp: timeStamp,
  randomString: randomString,
  MixedencryMD5: MixedencryMD5,
  isTel: isTel,
  isNum: isNum,
  imgMagnifyShow: imgMagnifyShow,
  uploadimg: uploadimg,
  getCurrentPageUrl: getCurrentPageUrl,
  throttle: throttle,
  payTap: payTap
}
